package evs.security.util;

import java.math.BigDecimal;

public class LocalAddress {
	
	String ipAddressLower;
	String ipAddressHigher;
	
	public LocalAddress(String ipAddress, String mask){
		ipAddressLower = getBinaryStringFromIp(ipAddress);
		ipAddressHigher = getLastAddressOfSubnet(ipAddressLower, Integer.parseInt(mask));
		
	}
	
	public boolean isIn(String ipAddress){
		BigDecimal ip = new BigDecimal(getBinaryStringFromIp(ipAddress));
		
		if(ip.compareTo(new BigDecimal(ipAddressLower)) >= 0 && ip.compareTo(new BigDecimal(ipAddressHigher)) <= 0){
			return true;
		}
		return false;
	}
	
	private String getBinaryStringFromIp(String ip){
		String result = "";
		String[] parts = ip.split("\\.");
		
		if(parts.length != 4){
			throw new NumberFormatException("No valid IP Address (" + ip + ")!");
		}
		for(String s : parts){
			String bin = Integer.toBinaryString(Integer.parseInt(s));
			while(bin.length() <8){
				bin = "0" + bin;
			}
			result += bin;
		}
		
		return result;
	}
	
	private String getLastAddressOfSubnet(String ipAddress, int mask){
		String ip = String.valueOf(ipAddress);
		String firstPart = ip.substring(0, mask);
		for (int i = mask; i < 32; i++){
			firstPart += "1";
		}
		
		return firstPart;
	}
}
